﻿using Microsoft.AspNetCore.Mvc;
using NewLife.Collections;
using Zdap.Common;
using Zdap.XCode;
using Zdap.XCode.Service;

namespace Datav.Web.Api.Controllers
{
    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="TDto"></typeparam>
    /// <remarks>
    ///
    /// </remarks>
    /// <param name="serviceFactory"></param>
    public class BaseAllController<TDto>(IServiceFactory serviceFactory) : BaseAllController<TDto, TDto>(serviceFactory) where TDto : class
    { }

   
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TDto"></typeparam>
    /// <typeparam name="TSeachDto"></typeparam>
    public class BaseAllController<TDto, TSeachDto> : BaseController where TDto : class where TSeachDto : class
    {
        ////  public String UserHost => HttpContext.GetUserHost();
        ///// <summary>
        /////
        ///// </summary>
        //public String UserHost => "";

        /// <summary>
        ///
        /// </summary>
        public IServiceBase<TDto>? _serviceBase = null;

        /// <summary>
        ///
        /// </summary>
        public ISearchServiceBase<TSeachDto>? _serviceSearchBase = null;

        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceFactory"></param>
        public BaseAllController(IServiceFactory serviceFactory) : base(serviceFactory)
        {
            _serviceBase = _serviceFactory.Resolve<IServiceBase<TDto>>();
            _serviceSearchBase = _serviceFactory.Resolve<ISearchServiceBase<TSeachDto>>();
        }

        /// <summary>
        /// 是否附加当前用户作为搜索参数
        /// </summary>
        protected virtual bool AppendCurrentUserAsSearchParam { get; }

        #region 增删改

        /// <summary>
        /// 新增和编辑对象
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ResponseContext<long>> Save(TDto dto)
        {
            if (dto == null)
            {
                return ModelStateError<long>();
            }

            return await _serviceBase.Save(dto, CurrentUser);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        [NonAction]
        public virtual async ValueTask<ResponseContext<List<long>>> BatchSave(SavaListModel<TDto> model)
        {
            return await _serviceBase.BatchSave(model, CurrentUser);
        }

        /// <summary>
        /// 删除单个数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public virtual async ValueTask<ResponseContext<bool>> Delete(long id)
        {
            return await _serviceBase.Delete(id, CurrentUser);
        }

        /// <summary>
        /// 删除多个数据
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public virtual async ValueTask<ResponseContext<bool>> DeleteByIds(IEnumerable<long> ids)
        {
            return await _serviceBase.DeleteIds(ids, CurrentUser);
        }

        #endregion 增删改

        #region 数据获取

        /// <summary>搜索数据集 (分页)</summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<PageResponseContext<TSeachDto>> Search(Pager p)
        {
            p.Params ??= new NullableDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            if (AppendCurrentUserAsSearchParam)
            {
                p.Params.Add("CurrentUser", CurrentUser);
            }

            return await _serviceSearchBase.Search(p);
        }

        /// <summary>
        /// 搜索列表前端自定查询字段,多个字段自动拼接成AND查询 （不分页）
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ListResponseContext<TSeachDto>> SearchBy(RequestParameter p)
        {
            p.Params ??= new NullableDictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            if (AppendCurrentUserAsSearchParam)
            {
                p.Params.Add("CurrentUser", CurrentUser);
            }

            return await _serviceSearchBase.SearchAll(p);
        }

        /// <summary>查找单行数据</summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ResponseContext<TDto>> FindByID(long ID)
        {
            return await _serviceBase.FindById(ID);
        }

        /// <summary>
        /// 按条件查询 单条信息
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual async Task<ResponseContext<TDto>> FindBy(RequestParameter p)
        {
            return await _serviceBase.FindBy(p);
        }

        ///// <summary>
        ///// 获取对象字段列表
        ///// </summary>
        ///// <returns></returns>
        //[AllowAnonymous]
        //[HttpGet]
        //public ListResponseContext<ColumnDataModel> GetColumnDataModel()
        //{
        //    return _serviceSearchBase.GetColumnDataModel();
        //}

        #endregion 数据获取

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="UploadFolder"></param>
        /// <returns></returns>
        ///
        //[HttpPost]
        //public virtual Task<ResponseContext<string>> Upload(List<Microsoft.AspNetCore.Http.IFormFile> files, string UploadFolder = "")
        //{
        //    var rest = new ResponseContext<string>();
        //    if (files == null || files.Count == 0)
        //        return Task.FromResult(rest.SetError("请上传文件"));

        //    string filePath;
        //    if (!string.IsNullOrEmpty(UploadFolder))
        //    {
        //        filePath = UploadFolder;
        //        if (!filePath.EndsWith("/") || !filePath.EndsWith("\\"))
        //        {
        //            filePath += "/";
        //        }
        //    }
        //    else
        //    {
        //        filePath = $"Uploads/{UploadFolder}/Tables/{DateTime.Now.ToString("yyyMMddHHmmsss") + new Random().Next(1000, 9999)}/";
        //    }
        //    string fullPath = filePath;//.MapPath(true);
        //    int i = 0;
        //    try
        //    {
        //        if (!Directory.Exists(fullPath))
        //            Directory.CreateDirectory(fullPath);
        //        for (i = 0; i < files.Count; i++)
        //        {
        //            string fileName = files[i].FileName;
        //            using (var stream = new FileStream(fullPath + fileName, FileMode.Create))
        //            {
        //                files[i].CopyTo(stream);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return Task.FromResult(rest.SetError(ex.Message));
        //    }
        //    return Task.FromResult(rest.SetSuccess(filePath, "文件上传成功"));
        //}
    }
}